import { buy, Check, GetRole, index } from '@/services/chdtuan';
import {
  PageContainer,
  ProForm,
  ProFormDigit,
  ProFormText,
} from '@ant-design/pro-components';
import { Button, Card, Form, Modal, Progress, Result, Space, Spin } from 'antd';
import { round, toNumber } from 'lodash-es';
import { useEffect, useRef, useState } from 'react';

const { Meta } = Card;
const onceNum = 5;
const timer = 5500;

const CardRender = ({ card, onBuy }) => {
  return (
    <Card
      style={{
        width: 260,
      }}
      cover={<img src={card.img} alt="example"></img>}
      actions={[
        <Button key="buy" onClick={() => onBuy(card)}>
          购买
        </Button>,
      ]}
    >
      <Meta
        title={card.title}
        description={<div className="pre">{card.desc.join('\n')} </div>}
      ></Meta>
    </Card>
  );
};

export default () => {
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<any>([]);
  const [step, setStep] = useState(0);
  const [form] = Form.useForm();
  const [goodsData, setGoodsData] = useState<{
    ID: string;
    Price: number;
    Num: number;
  }>();
  const [propNum, setPropNum] = useState(0);
  const isBuy = useRef(false);

  const init = () => {
    setLoading(true);
    return index()
      .then((res) => {
        setList(res.data);
        GetRole();
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // 关闭
  const onCancel = () => {
    setStep(0);
  };

  const onBuy = (data) => {
    setStep(1);
    const Price = data.desc[0].match(/团购价：(.*?)点券/)[1];

    form.setFieldsValue({
      ID: data.id,
      Name: data.title,
      Price: toNumber(Price),
      Num: 1,
    });
  };

  const send = ({ num, current, data }) => {
    return new Promise((res, rej) => {
      setTimeout(
        async () => {
          try {
            const res = await buy(data.ID);
            const { Timestamp, Sign } = res.data;
            await Check({
              ...data,
              Num: num,
              Timestamp,
              Sign,
            });
          } catch (error) {}

          console.log(`Resuest ${current} ${num}`);

          res(1);
        },
        current - num === 0 ? 0 : timer,
      );
    });
  };

  //  已购买数量  总数
  const onPolling = ({ current, total, data }) => {
    const num = total - current > onceNum ? onceNum : total - current;

    if (num === 0) {
      setPropNum(0);
      return;
    } else if (isBuy.current === false) {
      return;
    }

    send({ num, current: current + num, data }).then(() => {
      setPropNum(total - current - num);
      onPolling({
        current: current + num,
        total,
        data,
      });
    });
  };

  const onOk = () => {
    const formData = form.getFieldsValue();

    const { Name, ...data } = formData;

    setPropNum(data.Num);
    setGoodsData(data);
    setStep(2);
    isBuy.current = true;

    onPolling({
      current: 0,
      total: data.Num,
      data,
    });
  };

  const stepMap: any = {
    1: {
      title: '结算确认',
      mainRender() {
        return (
          <ProForm
            form={form}
            submitter={false}
            layout="horizontal"
            style={{
              marginTop: 24,
            }}
            labelCol={{
              span: 6,
            }}
          >
            <ProFormText width="md" name="ID" label="ID" readonly />
            <ProFormText width="md" name="Name" label="名称" readonly />
            <ProFormDigit width="md" name="Price" label="单价" readonly />
            <ProFormDigit
              width="md"
              name="Num"
              label="购买次数"
              initialValue={1}
              min={1}
              max={400}
              fieldProps={{
                precision: 0,
              }}
            />
          </ProForm>
        );
      },
      footer: [
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button key="buy" type="primary" onClick={onOk}>
          确认购买
        </Button>,
      ],
    },
    2: {
      mainRender() {
        if (!goodsData) return null;
        const percent = round(
          ((goodsData?.Num - propNum) / goodsData.Num) * 100,
          1,
        );

        const title =
          propNum === 0
            ? `全部消费完毕，共计${goodsData.Num}次`
            : `批量消费中，剩余次数：${propNum}`;

        const extra = propNum !== 0 && (
          <Button
            onClick={() => {
              isBuy.current = !isBuy.current;

              onPolling({
                current: goodsData?.Num - propNum,
                total: goodsData.Num,
                data: goodsData,
              });
            }}
          >
            暂停/继续
          </Button>
        );
        return (
          <Result
            title={title}
            extra={extra}
            icon={
              <Progress
                type="circle"
                percent={percent}
                strokeColor={{
                  '0%': '#87d068',
                  '50%': '#ffe58f',
                  '100%': '#ffccc7',
                }}
              />
            }
          />
        );
      },
      footer: [],
    },
  };

  useEffect(() => {
    init();
  }, []);

  return (
    <Spin spinning={loading}>
      <PageContainer
        header={{
          title: '',
        }}
      >
        <Space size={[24, 24]} wrap>
          {list.map((card) => {
            return <CardRender key={card.id} card={card} onBuy={onBuy} />;
          })}
        </Space>

        <Modal
          title={stepMap[step]?.title}
          open={step > 0}
          onOk={onOk}
          onCancel={() => setStep(0)}
          afterClose={() => {
            form.resetFields();
            setStep(0);
            setGoodsData(undefined);
            isBuy.current = false;
          }}
          footer={stepMap[step]?.footer}
          destroyOnClose
        >
          {stepMap[step]?.mainRender()}
        </Modal>
      </PageContainer>
    </Spin>
  );
};
